package com.tungse.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.util.CharsetUtil;

public class NettyClient {
    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                     .channel(NioSocketChannel.class)
                     .handler(new ChannelInitializer<SocketChannel>() {
                         @Override
                         protected void initChannel(SocketChannel ch) {
                             // 1. 客户端编码：消息头（4字节长度）+ 消息体
                             ch.pipeline().addLast(new LengthFieldPrepender(4)); // 长度字段占4字节

                             // 2. 解码（与服务端一致）
                             ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(
                                     1024, 0, 4, 0, 4
                             ));

                             // 3. 自定义业务处理器
                             ch.pipeline().addLast(new ClientHandler());
                         }
                     });

            ChannelFuture future = bootstrap.connect("127.0.0.1", 8080).sync();
            System.out.println("Netty 客户端连接成功...");
            
            // 模拟发送多条消息（测试粘包拆包）
            for (int i = 0; i < 5; i++) {
                String msg = "Message #" + i;
                ByteBuf buf = Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8);
                future.channel().writeAndFlush(buf);
                Thread.sleep(500);
            }

            future.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
}